package com.open.capacity.client.filter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.station.common.util.CommonResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.open.capacity.common.constant.UaaConstant;
import com.open.capacity.common.util.TokenUtil;

/**
 * Created by owen on 2017/9/10.
 */
@Component
@SuppressWarnings("all") 
public class AccessFilter extends ZuulFilter {

	@Value("#{'${pathList}'.split(',')}")
	private List<String> pathList;

	@Override
	public String filterType() {
		return "pre";
	}

	@Override
	public int filterOrder() {
		return 0;
	}

	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public Object run() {

		RequestContext requestContext = RequestContext.getCurrentContext();
		HttpServletResponse response = requestContext.getResponse();
		response.setContentType("text/html;charset=UTF-8");
		HttpServletRequest request = requestContext.getRequest();
		String uri = request.getRequestURI();
		// 那些路径可以直接放行
		boolean a = pathList.stream().anyMatch(path-> StringUtils.contains(uri, path));
		if (a){
			return null;
		}

		String authorization = request.getHeader("Authorization");
		if (StringUtils.isBlank(authorization)){
			String referer = request.getHeader("referer");
			if(("http://localhost:10000/swagger-ui.html").equals(referer)){
				return null;
			}


//            requestContext.setResponseBody("为获取到token");
			CommonResult<Object> commonResult = CommonResult.unauthorized(null);
			String jsonStr = JSONObject.toJSONString(commonResult);
			requestContext.setResponseBody(jsonStr);
			requestContext.setSendZuulResponse(false);
			return null;

		}
		String token = StringUtils.substring(authorization,"bearer".length()).trim();



		// 第二种方法：远程调用验证(复杂的认证)
		checkLongRange(token,requestContext,uri);

		return null;
	}


    // 第二种方法：远程调用验证(复杂的认证)
    private Object checkLongRange(String token, RequestContext requestContext, String uri) {
        try {
            boolean tokenExpired = jwtService.isTokenExpired(token);
            if (tokenExpired){
                String jsonStr = JSONObject.toJSONString(CommonResult.unauthorized(null));

                requestContext.setResponseBody(jsonStr);
                requestContext.setSendZuulResponse(false);
                return null;
            }
        } catch (Exception e) {
            // 处理token过期
            if(e instanceof ExpiredJwtException){
                String jsonStr = JSONObject.toJSONString(CommonResult.unauthorized(null));

                requestContext.setResponseBody(jsonStr);
                requestContext.setSendZuulResponse(false);
                return null;
            }
            e.printStackTrace();
        }
        CommonResult commonResult = jwtFeign.checkAccessToUri(uri, jwtService.getUserNameFromToken(token));
        if (commonResult.getCode() == 200){
            return null;
        } else if (commonResult.getCode() == 403){
            String jsonStr = JSONObject.toJSONString(CommonResult.forbidden(null));

            requestContext.setResponseBody(jsonStr);
            requestContext.setSendZuulResponse(false);
            return null;
        }
        return null;
    }

}
